package service

import (
	"errors"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"
	"strings"
	"vrcm/src/vrcm/app/admin/models/view"
	"vrcm/src/vrcm/app/admin/service/dto/view_manage"
	"vrcm/src/vrcm/common/apis"

	"vrcm/src/vrcm/common/actions"
	cDto "vrcm/src/vrcm/common/dto"
)

type ViewFit struct {
	service.Service
}

// GetPage 获取ViewFit列表
func (e *ViewFit) GetPage(c *view_manage.ViewFitGetPageReq, p *actions.DataPermission, list *[]view.ViewFit, count *int64) error {
	var err error
	var data view.ViewFit

	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
		).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("ViewFitService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

// Get 获取ViewFit对象
func (e *ViewFit) Get(d *view_manage.ViewFitGetReq, model *view.ViewFit) error {
	//var data models.ViewFit

	err := e.Orm.Where(map[string]interface{}{"bind_id": d.GetBindId()}).First(model).Error
	//err := e.Orm.Model(model).Where("bind_id=?", d.GetBindId()).Limit(1).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("Service GetViewFit error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

// Insert 创建ViewFit对象
func (e *ViewFit) Insert(c *view_manage.ViewFitInsertReq) error {
	var err error
	var data view.ViewFit
	c.Generate(&data)
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("ViewFitService Insert error:%s \r\n", err)
		return err
	}
	return nil
}

// Update 修改ViewFit对象
func (e *ViewFit) Update(c *view_manage.ViewFitUpdateReq, p *actions.DataPermission) error {
	var err error
	var data = view.ViewFit{}

	if len(c.BackUrl) > 0 {
		b := e.IsImageURL(c.BackUrl)
		if !b {
			return errors.New(string(apis.ImageError.Code))
		}
	}

	if len(c.Logo) > 0 {
		b := e.IsImageURL(c.Logo)
		if !b {
			return errors.New(string(apis.ImageError.Code))
		}
	}
	e.Orm.Scopes(
		actions.Permission(data.TableName(), p),
	).First(&data, c.GetId())
	c.Generate(&data)

	db := e.Orm.Save(&data)
	if err = db.Error; err != nil {
		e.Log.Errorf("ViewFitService Save error:%s \r\n", err)
		return err
	}
	return nil
}

func (e *ViewFit) IsImageURL(url string) bool {
	// 常见的图片文件扩展名
	imageExtensions := []string{".jpg", ".jpeg", ".png", ".gif", ".psd", ".bmp", ".tga", ".tiff", ".eps", ".svg", ".pdf"}

	// 将地址转换为小写字母，方便比较
	url = strings.ToLower(url)

	// 去掉链接中的 ? 及其后面的内容
	urlParts := strings.Split(url, "?")
	urlPart := urlParts[0]

	// 检查地址是否以图片文件扩展名结尾
	for _, ext := range imageExtensions {
		if strings.HasSuffix(urlPart, ext) {
			return true
		}
	}

	return false
}

// Remove 删除ViewFit
func (e *ViewFit) Remove(d *view_manage.ViewFitDeleteReq, p *actions.DataPermission) error {
	var data view.ViewFit

	db := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).Delete(&data, d.GetId())
	if err := db.Error; err != nil {
		e.Log.Errorf("Service RemoveViewFit error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

func (e *ViewFit) GetInfoByBindId(d *view_manage.ViewReq) (view_manage.ViewRes, error) {
	var fit view.ViewFit
	var limit view.ViewLimit
	var res view_manage.ViewRes
	e.Orm.Model(view.ViewFit{}).Where("bind_id =?", d.BindId).Find(&fit)
	e.Orm.Model(view.ViewLimit{}).Where("bind_id =?", d.BindId).Find(&limit)
	if fit.Id <= 0 {
		res.Fit = nil
	} else {
		res.Fit = &fit
	}
	if limit.Id <= 0 {
		res.Limit = nil
	} else {
		res.Limit = &limit
	}
	return res, nil
}
